<template>
	<view class="container">
		<uni-segmented-control :current="currentIndex" :values="items" style-type="text" active-color="#007aff"
			@clickItem="onClickItem" />

		<view v-if="currentIndex === 0">
			<view style="padding-top: 10px;"></view>

			<uni-forms ref="baseForm" :modelValue="zhuanzhengApplyForm" :border="true" labelWidth="100px"
				label-position="left">
				
				<uni-forms-item label="转正员工" required>
					<view >
						<button  @click="clickSelectZhuanzhengUser" class="btn-add" v-if="zhuanzhengApplyForm.zhuanzhengUser.length != 0">{{zhuanzhengApplyForm.zhuanzhengUser[0].name}}</button>
					</view>
					<view >
						<button  @click="clickSelectZhuanzhengUser" class="btn-add" v-if="zhuanzhengApplyForm.zhuanzhengUser.length == 0">选择员工</button>
					</view>
				</uni-forms-item>
				<uni-forms-item label="工号">
					<uni-easyinput :inputBorder="false" :placeholder="getZhuanzhengUid()" disabled ></uni-easyinput>
				</uni-forms-item>				
				<uni-forms-item label="入职时间">
					<uni-easyinput :inputBorder="false" :placeholder="getRuzhiDate()" disabled ></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item label="试用期" required>
					<!-- 无试用期、1个月，2个月，3个月，4个月、5个月、6个月、其他；写死，无需管理 -->
					<picker type="default" :range="shiyongqiStrs" @change="shiyongqiChange" >

						<view class="picker-bg">{{shiyongqiStr()}}</view>
					</picker>
				</uni-forms-item>

				<uni-forms-item label="转正时间">
					<uni-easyinput :inputBorder="false" :placeholder="zhuanzhengDate()" disabled ></uni-easyinput>
				</uni-forms-item>

				<uni-forms-item label="部门" required>
					<picker type="default" :range="departNames" @change="departChange" >
						<view class="picker-bg">{{departNameStr()}}</view>
					</picker>
				</uni-forms-item>
				<uni-forms-item label="岗位" required>
					<picker type="default" :range="posNames" @change="posChange" >
						<view class="picker-bg">{{posNameStr()}}</view>
					</picker>
				</uni-forms-item>
				<!-- 选择单人模板 -->
				<uni-forms-item label="上级主管" required>
					<view >
						<button @click="clickSelectUpper" class="btn-add" v-if="zhuanzhengApplyForm.upper.length != 0">{{zhuanzhengApplyForm.upper[0].name}}</button>
					</view>
					<view >
						<button @click="clickSelectUpper" class="btn-add" v-if="zhuanzhengApplyForm.upper.length == 0">选择上级主管</button>
					</view>
				</uni-forms-item>

				<!-- 选人模块 -->
				<uni-forms-item label="审核人" required></uni-forms-item>
				<view v-for="(item, idx) in zhuanzhengApplyForm.auditors" :key="idx">
					<uni-row>
						<uni-col :span="10">
							<view v-if="idx>0" class="step-arrow">
								<uni-icons type="bottom" size="mini" color='#a5eaff'></uni-icons>
							</view>
						</uni-col>
					</uni-row>
				
					<view class="step">
						<uni-row>
							<uni-col :span="10">
								<view class="step-info-left">{{item.stepName || item.positionName}}</view>
							</uni-col>
							<uni-col :span="14">
								<view class="step-info-right">{{item.name}}</view>
							</uni-col>
						</uni-row>
					</view>
				</view>
				

				<view style="padding-top: 30px;"></view>
				<button type="primary" @click="clickApply">提交</button>
			</uni-forms>
		</view>
		<view v-if="currentIndex === 1">
			<view v-for="(item, idx) in applyRecord" style="padding-bottom: 10px;" :key="idx">
				<view class="card" @click="seeDetail(idx)">
					<view class="card-title">
						<uni-row>
							<uni-col :span="20">
								<view class="card-title-left">{{item.name}}</view>
							</uni-col>
							<uni-col :span="4">
								<view class="card-title-right">
									<uni-tag text="审核" size="mini" type="warning" v-if="item.sta===0&&item.chexiao==0"></uni-tag>
									<uni-tag text="通过" size="mini" type="primary" v-if="item.sta===1&&item.chexiao==0"></uni-tag>
									<uni-tag text="拒绝" size="mini" type="error" v-if="item.sta===2&&item.chexiao==0"></uni-tag>
									<uni-tag text="撤销" size="mini" type="default" v-if="item.chexiao===1"></uni-tag>
								</view>
							</uni-col>
						</uni-row>
					</view>
					<view class="card-body">
						<view>部门：{{item.department}}</view>
						<view>岗位：{{item.position}}</view>
						<view>主管：{{item.upper}}</view>
						<view>入职时间：{{item.ruzhiDate}}</view>
					</view>
					<view class="card-footer">
						<uni-row>
							<uni-col :span="24">
								<view class="card-footer-right">
									{{getFormatedTimeStr(item.createTime)}}
								</view>
							</uni-col>
						</uni-row>
					</view>
				</view>
			</view>

			<uni-load-more :status="moreStatus"></uni-load-more>
		</view>

	</view>
</template>

<script>
	import moment from 'moment'
	import { websock } from '../../net/websock'
	import {uploadconfig} from '../../const'
	import { quchongAuditors } from '../../utils/util'

	export default {
		data() {
			return {
				// 上传参数部分没有事情不要乱动
				uploadconfig,
				option: {
					url:uploadconfig.url,
					name: 'file',
					header: {},
					formData: {}
				},
				formats:uploadconfig.formats,
				instantly: uploadconfig.instantly,
				size: uploadconfig.size,
				files: new Map(),
				// 上传参数部分没有事情不要乱动
				currentIndex: 0,
				items: ['转正申请', '转正记录'],
				shiyongqiStrs: ['','无试用期','一个月','两个月','三个月','四个月','五个月','六个月'],
				departNames: [''],
				departIds: [],
				departIndex: -1,
				posNames: [''],
				posIds: [],
				posIndex: 0,
				userInfo: {},
				moreStatus: 'more',
				applyRecord: [],
				auditors: [],
				zhuanzhengApplyForm: {
					department: '',
					position: '',
					degree: '',
					shiyongqi: 0,
					zhuanzhengTime: '',
					upper: [],
					zhuanzhengUser: [],
					auditors: []
				}
			}
		},
		async onReady() {
			console.log('zhuanzheng shenqing on ready')

			try {
				this.userInfo = await websock.getUserInfo()

				let departList = await websock.getDepartList()
				for (let i = 0; i != departList.length; i++) {
					this.departNames.push(departList[i].name)
					this.departIds.push(departList[i].id)
				}
				console.log('depart list', departList)

				let posList = await websock.getPosList()
				for (let i = 0; i != posList.length; i++) {
					this.posNames.push(posList[i].name)
					this.posIds.push(posList[i].id)
				}
				console.log('pos list', posList)

				this.auditors = await websock.getAuditors({typ: 4})

				this.getAuditors()

				this.getNewestRecord()
			} catch (e) {
				uni.showToast({
					title: e.message
				})
			}
		},
		// 下拉刷新，获取最新的数据
		onPullDownRefresh() {
			console.log('onPullDownRefresh')
			if (this.currentIndex == 0) {
				uni.stopPullDownRefresh()
			} else {
				this.getNewestRecord()
			}
		},
		// 上拉刷新，获取历史数据
		onReachBottom() {
			console.log('onReachBottom')
			if (this.currentIndex == 1) {
				this.getOlderRecord()
			}
		},
		methods: {
			// 附件上传恶心的代码块-------------------------------------------------------------
			// 某文件上传结束回调(成功失败都回调)
			onuploadEnd(item) {
				console.log('fuck you',3)
				if (item.type == 'fail') {
					return uni.showToast({title: '上传失败'})}
				try {
					let res = JSON.parse(item.responseText)
					if (res.code !== 0) {
						return uni.showToast({title: res.message || 'error'})}
					this.zhuanzhengApplyForm.attaches.push({name: item.name, path: res.data})
				} catch (err) {
					uni.showToast({title: err.message})}
				this.$forceUpdate();
			},
			// 上传进度回调
			onprogress(item) {
				this.files.set(item.name,item);// 更新当前状态变化的文件
				this.$forceUpdate();// 强制更新视图
			},
			// 文件选择回调
			onChange(files) {
				this.files = files;// 更新选择的文件 
				this.$forceUpdate();// 强制更新视图
			},
			// 穿刺一击让他们的遮罩层消失
			chuanci(){
				this.$refs.lsjUpload && this.$refs.lsjUpload.hide();
			},
			// 穿刺一击让他们的遮罩层消失
			chuanci2(){
				this.$refs.lsjUpload && this.$refs.lsjUpload.show();
				this.$forceUpdate()
			},
			// 强制重置附件按钮,万一出意外点2次按钮至少可以进去
			fuckyou(){
				this.$refs.lsjUpload && this.$refs.lsjUpload.hide()
				this.$refs.lsjUpload && this.$refs.lsjUpload.show()
				this.$forceUpdate()
			},
			// 附件上传恶心的代码块-------------------------------------------------------------
			// 获取最新的通知
			async getNewestRecord() {
				try{
					if (this.applyRecord.length == 0) {
						let res = await websock.zhuanzhengApplyRecord({pageCount: 10})
						console.log('getRecordList list empty', res)
						uni.stopPullDownRefresh()
						this.applyRecord = [...res, ...this.applyRecord]
					} else {
						let res = await websock.zhuanzhengApplyRecord({greaterThan: this.applyRecord[0].id,pageCount: 10})
						console.log('getRecordList list not empty', res)
						uni.stopPullDownRefresh()
						this.applyRecord = [...res, ...this.applyRecord]
					}
				}catch(e){
					uni.showToast({title: e.message})
				}
			},
			// 获取格式化时间字符串
			getFormatedTimeStr(stamp, str='MM-DD HH:mm:ss') {
				return moment(stamp).format(str)
			},
			async getAuditors() {
				try {
					this.zhuanzhengApplyForm.auditors = []
					let defaultAuditors = this.auditors.slice()
					for (let i = 0; i != defaultAuditors.length; i++) {
						if (defaultAuditors[i].sta == '0') {
							this.zhuanzhengApplyForm.auditors.push(defaultAuditors[i])
						} else if (defaultAuditors[i].sta == '1') {
							if (this.departIndex == -1) continue
							let departId = this.departIds[this.departIndex]
							let lingdao = await websock.getDepartmentLingdao({departId})
							if (lingdao.fenguan_lingdao) {
								this.zhuanzhengApplyForm.auditors.push({uid: lingdao.fenguan_lingdao, name: lingdao.fenguan_lingdao_name, positionName: lingdao.fenguan_lingdao_position_name})
							}
						}
					}
					quchongAuditors(this.zhuanzhengApplyForm.auditors)
				} catch (err) {
					console.error(err)
					uni.showToast({title: '获取审核人失败'})
				}
			},
			// 获取老的数据
			async getOlderRecord() {
				this.moreStatus = 'loading'
				try{
					if (this.applyRecord.length == 0) {
						console.log('before get list empty')
						let res = await websock.zhuanzhengApplyRecord({pageCount: 10})
						console.log('getOlderRecord list empty', res)
						this.applyRecord = [...this.applyRecord, ...res]
						if (res.length < 10) {
							this.moreStatus = 'noMore'
						} else {
							this.moreStatus = 'more'
						}
					} else {
						console.log('before get list not empty')
						let res = await websock.zhuanzhengApplyRecord({lessThan: this.applyRecord[this.applyRecord.length - 1].id,pageCount: 10})
						console.log('getOlderRecord list not empty', res)
						this.applyRecord = [...this.applyRecord, ...res]
						if (res.length < 10) {
							this.moreStatus = 'noMore'
						} else {
							this.moreStatus = 'more'
						}
					}
				}catch(e){
					uni.showToast({title: e.message})
				}
			},
			onClickItem(e) {
				if (this.currentIndex !== e.currentIndex) {
					this.currentIndex = e.currentIndex
				}
			},
			clickSelectAuditor() {
				uni.navigateTo({
					url: '/pages/common/contactSelect?selectedUsers=' + JSON.stringify(this.zhuanzhengApplyForm.auditors || []),
					events: {
						contactList: data => {
							console.log('select auditor', data)
							this.zhuanzhengApplyForm.auditors = data.contactList
						}
					}
				})
			},
			clickSelectUpper() {
				uni.navigateTo({
					url: '/pages/common/contactSelect?selectedUsers=' + JSON.stringify(this.zhuanzhengApplyForm.upper || []) + '&isSingle=1',
					events: {
						contactList: data => {
							console.log('select auditor', data)
							this.zhuanzhengApplyForm.upper = data.contactList
						}
					}
				})
			},
			clickSelectZhuanzhengUser() {
				uni.navigateTo({
					url: '/pages/common/contactSelect?selectedUsers=' + JSON.stringify(this.zhuanzhengApplyForm.zhuanzhengUser || []) + '&isSingle=1',
					events: {
						contactList: data => {
							console.log('select auditor', data)
							if (data.contactList[0].sta != '试用') {
								return uni.showToast({title: '不在试用期'})
							}
							this.zhuanzhengApplyForm.zhuanzhengUser = data.contactList
						}
					}
				})
			},
			departChange(e) {
				console.log('depart change', e.detail.value)
				this.departIndex = e.detail.value
				this.getAuditors()
			},
			departNameStr() {
				return this.departNames[this.departIndex] || ''
			},
			posChange(e) {
				console.log('pos change', e.detail.value)
				this.posIndex = e.detail.value
			},
			posNameStr() {
				return this.posNames[this.posIndex] || ''
			},
			shiyongqiStr() {
				return this.shiyongqiStrs[this.zhuanzhengApplyForm.shiyongqi] || ''
			},
			shiyongqiChange(e) {
				this.zhuanzhengApplyForm.shiyongqi = e.detail.value
			},
			// 计算转正日期
			zhuanzhengDate() {
				if (this.zhuanzhengApplyForm.zhuanzhengUser.length == 0) return ''
				return moment(this.zhuanzhengApplyForm.zhuanzhengUser[0].ruzhiDate).add(this.zhuanzhengApplyForm.shiyongqi, 'months').format('YYYY-MM-DD')
			},
			// 获取转正员工工号
			getZhuanzhengUid() {
				if (this.zhuanzhengApplyForm.zhuanzhengUser.length == 0) return ''
				return this.zhuanzhengApplyForm.zhuanzhengUser[0].uid
			},
			// 获取转正员工入职日期
			getRuzhiDate() {
				if (this.zhuanzhengApplyForm.zhuanzhengUser.length == 0) return ''
				return moment(this.zhuanzhengApplyForm.zhuanzhengUser[0].ruzhiDate).format('YYYY-MM-DD')
			},
			async clickApply() {
				console.log('zhuanzheng apply click apply', this.zhuanzhengApplyForm)

				if (this.zhuanzhengApplyForm.auditors.length == 0) return uni.showToast({ title: '请选择审核人' })

				if (this.zhuanzhengApplyForm.upper.length == 0) return uni.showToast({ title: '请选择上级主管' })

				if (this.zhuanzhengApplyForm.zhuanzhengUser.length == 0) return uni.showToast({ title: '请选择转正员工' })

				if (this.departIndex == -1) return uni.showToast({ title: '请选择部门' })

				let auditors = []
				for (let i = 0; i != this.zhuanzhengApplyForm.auditors.length; i++) {
					auditors.push({uid: this.zhuanzhengApplyForm.auditors[i].uid, stepName: this.zhuanzhengApplyForm.auditors[i].stepName || this.zhuanzhengApplyForm.auditors[i].positionName})
				}

				try {
					await websock.zhuanzhengApply({
						name: this.userInfo.name,
						ruzhiDate: this.zhuanzhengApplyForm.zhuanzhengUser[0].ruzhiDate,
						shiyongqi: this.shiyongqiStr(),
						zhuanzhengDate: this.zhuanzhengDate(),
						zhuanzhengUser: this.zhuanzhengApplyForm.zhuanzhengUser[0].uid,
						zhuanzhengUserName: this.zhuanzhengApplyForm.zhuanzhengUser[0].name,
						department: this.departNames[this.departIndex],
						departmentId: this.departIds[this.departIndex],
						position: this.posNames[this.posIndex],
						positionId: this.posIds[this.posIndex],
						upper: this.zhuanzhengApplyForm.upper[0].name,
						upperId: this.zhuanzhengApplyForm.upper[0].uid,
						auditors
					})

					uni.showToast({ title: '提交成功' })
					this.zhuanzhengApplyForm = {
						departName: '',
						posName: '',
						degree: '',
						shiyongqi: 0,
						zhuanzhengTime: '',
						upper: [],
						zhuanzhengUser: [],
						auditors: []
					}

					this.departIndex = -1

					this.currentIndex = 1

					this.getNewestRecord()
				} catch (err) {
					uni.showToast({ title: err.message || 'error' })
				}
			},
			async revertApply(idx) {
				try {
					await websock.revertZhuanzhengApply({id: this.applyRecord[idx].id})
					this.applyRecord[idx].sta = 4
				} catch (err) {
					console.error(err)
					uni.showToast({title: err.message || 'error'})
				}
			},
			seeDetail(idx) {
				uni.navigateTo({url: `/pages/task/zhuanzhengApplyDetail?id=${this.applyRecord[idx].id}`})
			}
		}
	}
</script>

<style>
@import '../common/common.css';
</style>